import React, { forwardRef, useContext, useState, useEffect } from 'react';
import CustomSelect from 'components/customselect';
import PromptInput from 'components/promptinput';
import { useTranslation } from 'react-i18next';
import useFormStore from 'src/context/usetypeformstore';
import ImageUploadList from 'components/imguploadlist';
import ExpandableSection from 'components/expandablesection';
import Slider from 'components/slider';

import '../forms.scss';
import classNames from 'classnames';
import { version } from 'prettier';

const ImageForm = () => {
    const { t, i18n } = useTranslation('home', {
        keyPrefix: 'generateleft',
    });

    const state = useFormStore();
    const { setFormData } = useFormStore();
    const formData = state.image;
    const models = state.modellist.image;
    // 用于跟踪从提示词中解析出的参数
    const [parsedParams, setParsedParams] = useState({});

    const options = models.map((item) => {
        const [key, value] = Object.entries(item)[0]; // 获取第一个键值对
        return {
            key: key,
            value: value,
            label: value,
        };
    });

    const styleOptions = [{ value: 0, label: '标准' }];

    const sketchOptions = [
        { value: 1, label: '开' },
        { value: 0, label: '关' },
    ];

    const speedOptions = [
        { value: 1, label: '快' },
        { value: 2, label: '中' },
        { value: 3, label: '慢' },
    ];

    const resolutionOptions = [
        { value: 'high', label: '高清' },
        { value: 'common', label: '普通' },
    ];

    const ratiolist = [
        { value: '1:1', label: '1:1', width: '12', height: '12', name: 'r1-1' },
        {
            value: '3:4',
            label: '3:4',
            width: '9',
            height: '12',
            name: 'r3-4',
        },
        {
            value: '2:3',
            label: '2:3',
            width: '8',
            height: '12',
            name: 'r2-3',
        },
        {
            value: '9:16',
            label: '9:16',
            width: '6.75',
            height: '12',
            name: 'r9-16',
        },
        {
            value: '1:2',
            label: '1:2',
            width: '6',
            height: '12',
            name: 'r2-1',
        },

        {
            value: '4:3',
            label: '4:3',
            width: '16',
            height: '12',
            name: 'r4-3',
        },
        {
            value: '3:2',
            label: '3:2',
            width: '18',
            height: '12',
            name: 'r3-2',
        },
        {
            value: '16:9',
            label: '16:9',
            width: '21.33',
            height: '12',
            name: 'r16-9',
        },
        {
            value: '2:1',
            label: '2:1',
            width: '24',
            height: '12',
            name: 'r1-2',
        },
    ];

    const [first, ...rest] = ratiolist;

    const KNOWN_PARAMS = new Set([
        'version',
        'v',
        'aspect',
        'ar',
        'turbo',
        'fast',
        'relax',
        'raw',
        'stylize',
        's',
        'chaos',
        'c',
        'weird',
        'w',
        'quality',
        'q',
    ]);

    const parsePrompt = (prompt) => {
        const result = {
            cleanPrompt: prompt,
            params: {},
        };

        // 匹配 --key 或 --key value
        const paramRegex = /--(\w+)(?:\s+((?!--)[^\s]+))?/g;
        let match;
        const matches = [];

        while ((match = paramRegex.exec(prompt)) !== null) {
            matches.push(match);
        }

        // 逆序处理，避免索引错乱
        const sortedMatches = matches.sort((a, b) => b.index - a.index);
        let cleaned = prompt;

        for (const match of sortedMatches) {
            const key = match[1].toLowerCase();

            // 只有在 KNOWN_PARAMS 中的参数才提取并从 prompt 中移除
            if (KNOWN_PARAMS.has(key)) {
                const value = match[2] !== undefined ? match[2] : true;
                result.params[key] = value;

                const fullMatch = match[0];
                cleaned =
                    cleaned.slice(0, match.index) +
                    cleaned.slice(match.index + fullMatch.length);
            }
        }

        result.cleanPrompt = cleaned.trim().replace(/\s+/g, ' ');
        return result;
    };
    const handlePromptChange = (e) => {
        setFormData('image', {
            ...formData,
            prompts: e.target.value,
        });

        //对value进行内容识别
        const { cleanPrompt, params } = parsePrompt(e.target.value);
        setParsedParams(params);
        if (params.version || params.v) {
            setFormData('image', {
                version: params.version || params.v,
            });
        }
        if (params.aspect || params.ar) {
            setFormData('image', {
                ratio: params.aspect || params.ar,
            });
        }
        if (params.turbo) {
            //极速模式
            setFormData('image', {
                speed: 1,
            });
        }
        if (params.fast) {
            //极速模式
            setFormData('image', {
                speed: 2,
            });
        }
        if (params.relax) {
            //极速模式
            setFormData('image', {
                speed: 3,
            });
        }
        if (params.raw) {
            //极速模式
            setFormData('image', {
                isRaw: 1,
            });
        }
        if (params.stylize || params.s) {
            setFormData('image', {
                stylize: (params.stylize || params.s) / 100,
            });
        }
        if (params.chaos || params.c) {
            setFormData('image', {
                diversity: (params.chaos || params.c) / 100,
            });
        }
        if (params.weird || params.w) {
            setFormData('image', {
                particularity: (params.weird || params.w) / 100,
            });
        }
        if (params.quality || params.q) {
            setFormData('image', {
                resolution:
                    (params.quality || params.q) == 2 ? 'high' : 'common',
            });
        }
    };

    // 检查是否有对应的参数被解析出来
    const isParamParsed = (paramNames) => {
        return Array.isArray(paramNames)
            ? paramNames.some((name) => parsedParams.hasOwnProperty(name))
            : parsedParams.hasOwnProperty(paramNames);
    };

    useEffect(() => {
        // 当提示词被清空时，清空解析的参数
        if (!formData.prompts) {
            setParsedParams({});
        }
    }, [formData.prompts]);

    return (
        <div className="text2video-form">
            <div className="form-group">
                <p className="type-selection-title">{t('modeltitle')}</p>

                <CustomSelect
                    formType="image"
                    fieldName="version"
                    options={options}
                    className="model-select"
                    placeholder="选择模型..."
                    disabled={isParamParsed(['version', 'v'])} // 禁用条件
                />
            </div>
            <div className="form-group">
                <p className="type-selection-title">{t('prompttitle')}</p>
                <PromptInput
                    value={formData.prompts}
                    onChange={handlePromptChange}
                    placeholder="输入你的提示词"
                ></PromptInput>
            </div>

            <div className="form-group">
                <p className="type-selection-title">{t('bRefstitle')}</p>
                <ImageUploadList
                    onFileChange={(files, urls) => {
                        setFormData('image', {
                            bRefs: urls,
                        });
                    }}
                    onDelete={(index) => {
                        // console.log('删除了第', index, '张图片');
                    }}
                    initialImages={formData.bRefs}
                    maxCount={3}
                    text="上传参考图"
                />
            </div>

            <div className="form-group">
                <p className="type-selection-title">{t('sRefstitle')}</p>
                <ImageUploadList
                    onFileChange={(files, urls) => {
                        setFormData('image', {
                            sRefs: urls,
                        });
                    }}
                    onDelete={(index) => {
                        // console.log('删除了第', index, '张图片');
                    }}
                    initialImages={formData.sRefs}
                    maxCount={3}
                    text="上传参考图"
                />
            </div>

            <div className="form-group">
                <p className="type-selection-title">{t('uRefstitle')}</p>
                <ImageUploadList
                    onFileChange={(files, urls) => {
                        setFormData('image', {
                            uRefs: urls,
                        });
                    }}
                    onDelete={(index) => {
                        // console.log('删除了第', index, '张图片');
                    }}
                    initialImages={formData.uRefs}
                    maxCount={1}
                    text="上传参考图"
                />
            </div>

            <div className="form-group">
                <p className="type-selection-title">{t('scaletitle')}</p>
                <div className="size-param">
                    <div
                        className={classNames(
                            'size-item first-item',
                            first.name,
                            {
                                'size-item-active':
                                    first.value === formData.ratio,
                            }
                        )}
                        onClick={() =>
                            !isParamParsed(['aspect', 'ar']) &&
                            setFormData('image', {
                                ratio: first.value,
                            })
                        }
                        key={first.value}
                        style={{
                            opacity: !isParamParsed(['aspect', 'ar']) ? 1 : 0.5,
                            cursor: isParamParsed(['aspect', 'ar'])
                                ? 'not-allowed'
                                : 'pointer',
                        }}
                    >
                        <div
                            className="size-item-rect"
                            style={{
                                width: first.width + 'px',
                                height: first.height + 'px',
                            }}
                        ></div>
                        <p>{first.label}</p>
                    </div>
                    {rest.map((item, index) => {
                        return (
                            <div
                                className={classNames('size-item', item.name, {
                                    'size-item-active':
                                        item.value === formData.ratio,
                                })}
                                onClick={() =>
                                    !isParamParsed(['aspect', 'ar']) &&
                                    setFormData('image', {
                                        ...formData,
                                        ratio: item.value,
                                    })
                                }
                                key={index}
                                style={{
                                    opacity: !isParamParsed(['aspect', 'ar'])
                                        ? 1
                                        : 0.5,
                                    cursor: isParamParsed(['aspect', 'ar'])
                                        ? 'not-allowed'
                                        : 'pointer',
                                }}
                            >
                                <div
                                    className="size-item-rect"
                                    style={{
                                        width: item.width + 'px',
                                        height: item.height + 'px',
                                    }}
                                ></div>
                                <p>{item.label}</p>
                            </div>
                        );
                    })}
                </div>
            </div>
            <div className="form-group">
                <ExpandableSection title={t('modelset')}>
                    <div className="modelset-content">
                        <div className="modelset-content-item">
                            <p className="modelset-content-item-title">
                                模型风格
                            </p>
                            <CustomSelect
                                formType="image"
                                fieldName="modelStyle"
                                options={styleOptions}
                                className="model-select"
                                placeholder="模型风格"
                                disabled={isParamParsed(['style'])}
                            />
                        </div>
                        <div className="modelset-content-item">
                            <p className="modelset-content-item-title">
                                草图模式
                            </p>
                            <CustomSelect
                                formType="image"
                                fieldName="isRaw"
                                options={sketchOptions}
                                className="model-select"
                                placeholder="草图模式"
                                disabled={isParamParsed('raw')} // 禁用条件
                            />
                        </div>
                    </div>
                </ExpandableSection>
            </div>
            <div className="form-group">
                <ExpandableSection
                    title="审美设置"
                    // style={{ paddingBottom: '2px' }}
                >
                    <Slider
                        title="风格化"
                        onChange={(value) => {
                            !isParamParsed(['stylize', 's']) &&
                                setFormData('image', {
                                    ...formData,
                                    stylize: value / 100,
                                });
                        }}
                        value={formData.stylize * 100}
                        style={{ marginBottom: '12px' }}
                        disabled={isParamParsed(['stylize', 's'])} // 禁用条件
                    ></Slider>
                    <div
                        className="modelset-content"
                        style={{ paddingBottom: '2px' }}
                    >
                        <div className="modelset-content-item">
                            <Slider
                                title="特殊性"
                                onChange={(value) => {
                                    !isParamParsed(['weird', 'w']) &&
                                        setFormData('image', {
                                            ...formData,
                                            particularity: value / 100,
                                        });
                                }}
                                value={formData.particularity * 100}
                                disabled={isParamParsed(['weird', 'w'])} // 禁用条件
                            ></Slider>
                        </div>
                        <div className="modelset-content-item">
                            <Slider
                                title="多样性"
                                onChange={(value) => {
                                    !isParamParsed(['chaos', 'c']) &&
                                        setFormData('image', {
                                            ...formData,
                                            diversity: value / 100,
                                        });
                                }}
                                value={formData.diversity * 100}
                                disabled={isParamParsed(['chaos', 'c'])}
                            ></Slider>
                        </div>
                    </div>
                </ExpandableSection>
            </div>
            <div className="form-group">
                <ExpandableSection title={'更多设置'}>
                    <div className="modelset-content">
                        <div className="modelset-content-item">
                            <p className="modelset-content-item-title">
                                生成速度
                            </p>
                            <CustomSelect
                                formType="image"
                                fieldName="speed"
                                options={speedOptions}
                                className="model-select"
                                placeholder="生成速度"
                                disabled={isParamParsed([
                                    'turbo',
                                    'fast',
                                    'relax',
                                ])} // 禁用条件
                            />
                        </div>
                        <div className="modelset-content-item">
                            <p className="modelset-content-item-title">
                                分辨率
                            </p>
                            <CustomSelect
                                formType="image"
                                fieldName="resolution"
                                options={resolutionOptions}
                                className="model-select"
                                placeholder="分辨率"
                                disabled={isParamParsed(['quality', 'q'])} // 禁用条件
                            />
                        </div>
                    </div>
                </ExpandableSection>
            </div>
        </div>
    );
};

export default ImageForm;
